package com.chuanyekeji.aokai.Controller;

import com.chuanyekeji.aokai.AokaiApplication;
import com.chuanyekeji.aokai.Config.ReadPathConfig;
import com.chuanyekeji.aokai.Entity.Model.ProductJsonModel;
import com.chuanyekeji.aokai.Entity.Product;
import com.chuanyekeji.aokai.Entity.ProductImage;
import com.chuanyekeji.aokai.Entity.ProductType;
import com.chuanyekeji.aokai.Entity.Seo;
import com.chuanyekeji.aokai.Mapper.ProductImageMapper;
import com.chuanyekeji.aokai.Mapper.ProductMapper;
import com.chuanyekeji.aokai.Mapper.ProductTypeMapper;
import com.chuanyekeji.aokai.Mapper.SeoMapper;
import com.chuanyekeji.aokai.Util.ReturnData;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.*;

@CrossOrigin(origins = "*",maxAge = 3600)
@RestController
public class ProductController {

    @Autowired
    ReadPathConfig readPathConfig;

    @Autowired
    ProductMapper productMapper;

    @Autowired
    ProductImageMapper productImageMapper;

    @Autowired
    ProductTypeMapper productTypeMapper;

    @Autowired
    SeoMapper seoMapper;
    /**
     * 添加商品
     * @param title
     * @param productDescribe
     * @param content
     * @param code
     * @return
     */
    @RequestMapping("addProduct")
    String addProduct(String productDescribe,String productDescribe_en,
                      String content,String code,String title,String title_en,String titles,
                      String descs,String keyword,String productTypeStr) {
        Seo seo = new Seo();
        seo.setTitle(titles);
        seo.setDescs(descs);
        seo.setKeyword(keyword);
        seo.setIsFirstPage(0);
        seoMapper.insertSelective(seo);

        //获取根目录
        String firstImagePath = "";
        try {
            firstImagePath = ResourceUtils.getURL("classpath:").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //获取文件上传时的项目相对路径
        File file = new File(firstImagePath,"static/" + readPathConfig.getImage());
        if(!file.exists()) {
            file.mkdirs();
        }
        String[] productTypes = productTypeStr.split("-");
        ProductType productType = productTypeMapper.selectByPrimaryKey(Integer.parseInt(productTypes[0]));
        Product product = new Product();
        product.setProductType(productType);
        product.setProductDescribe(productDescribe);
        product.setProductName(title);
        product.setProductDescribe_en(productDescribe_en);
        product.setProductName_en(title_en);
        product.setProductDetailed(content);
        product.setSeo(seo);
        productMapper.insertSelective(product);
        String[] images = code.split(";");
        for(String s : images) {
            ProductImage pi = new ProductImage();
            pi.setImageUrl(s);
            pi.setProduct(product);
            productImageMapper.insertSelective(pi);
        }
        return "发布成功";
    }

    /**
     * 获取商品详情
     * @param id
     * @return
     */
    @RequestMapping("getProduct")
    String getProduct(int id,HttpSession session) {
        Product product = productMapper.selectByPrimaryKey(id);
        Product nextProduct = productMapper.selectNextId(id);
        Product lastProduct = productMapper.selectLastId(id);
        Map<String,Object> data = new HashMap<>();
        int nextId = -1;
        int lastId = -1;
        String nextName = "";
        String lastName = "";
        if(nextProduct != null) {
            nextId = nextProduct.getId();
            nextName = nextProduct.getProductName();
        }
        if(lastProduct != null) {
            lastId = lastProduct.getId();
            lastName = lastProduct.getProductName();
        }
        if(AokaiApplication.language.get(session.getId()).equals("ch")) {
            data.put("data",product);
        } else if(AokaiApplication.language.get(session.getId()).equals("en")) {
            product.setProductDescribe(product.getProductDescribe_en());
            product.setProductName(product.getProductName_en());
        }
        data.put("nextPage",nextId);
        data.put("nextName",nextName);
        data.put("lastPage",lastId);
        data.put("lastName",lastName);
        System.out.println(new Gson().toJson(data));
        return ReturnData.success("success",new Gson().toJson(data));
    }

    /**
     * 获取商品分页数据
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping("getProductList")
    String getProductList(@RequestParam(required=false,defaultValue="0") int type,
                          @RequestParam(required=false,defaultValue="1") int page,
                          @RequestParam(required=false,defaultValue="10") int rows,
                          HttpSession session
    ) {
        int lastRow = rows * page;
        int indexRow = lastRow - rows;
        Map<String,Object> data = new HashMap<>();
        if(type == 0) {
            List<Product> productList = productMapper.getProductList(indexRow,lastRow);
            data.put("total",productMapper.getProductCount());
            if(!AokaiApplication.language.get(session.getId()).equals("en")) {
                data.put("rows",productList);
            } else if(AokaiApplication.language.get(session.getId()).equals("en")) {
                for(Product p : productList) {
                    p.setProductName(p.getProductName_en());
                    p.setProductDescribe(p.getProductName_en());
                }
                data.put("rows",productList);
            }
        } else {
            List<Product> productList = productMapper.getProductListByType(type,indexRow,lastRow);
            data.put("total",productMapper.getProductByTypeCount(type));
            if(!AokaiApplication.language.get(session.getId()).equals("en")) {
                data.put("rows",productList);
            } else if(AokaiApplication.language.get(session.getId()).equals("en")) {
                for(Product p : productList) {
                    p.setProductName(p.getProductName_en());
                    p.setProductDescribe(p.getProductName_en());
                }
                data.put("rows",productList);
            }
        }

        return ReturnData.success("success",data);
    }
    /**
     * 获取商品分页数据
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping("getProductListByJson")
    String getProductListByJson(@RequestParam(required=false,defaultValue="0") int type,
                          @RequestParam(required=false,defaultValue="1") int page,
                          @RequestParam(required=false,defaultValue="10") int rows) {
        int lastRow = rows * page;
        int indexRow = lastRow - rows;
        List<Product> productList = productMapper.getProductList(indexRow,lastRow);
        List<Product> countList = productMapper.getProductCount();
        List<ProductJsonModel> plist = new ArrayList<>();
        for(Product p : productList) {
            ProductJsonModel pjm = new ProductJsonModel();
            pjm.setId(p.getId());
            pjm.setSeoTitle(p.getSeo().getTitle());
            pjm.setSeoKeyword(p.getSeo().getKeyword());
            pjm.setSeoDescs(p.getSeo().getDescs());
            pjm.setProductType(p.getProductType().getProductTypeName());
            pjm.setProductName(p.getProductName());
            pjm.setProductName_en(p.getProductName_en());
            pjm.setProductDescribe(p.getProductDescribe());
            pjm.setProductName(p.getProductName());
            pjm.setProductDescribe_en(p.getProductDescribe_en());
            plist.add(pjm);
        }
        Map<String,Object> data = new HashMap<>();
        data.put("total",countList.size());
        data.put("rows",plist);
        return new Gson().toJson(data);
    }

    /**
     * 按照关键字搜索商品
     * @param page
     * @param rows
     * @param productName
     * @return
     */
    @RequestMapping("getProductByNameList")
    String getProductByNameList(@RequestParam(required=false,defaultValue="1") int page, @RequestParam(required=false,defaultValue="10") int rows,String productName) {
        int lastRow = rows * page;
        int indexRow = lastRow - rows;
        List<Product> productList = productMapper.getProductByNameList(indexRow,lastRow,"%" + productName + "%");
        Map<String,Object> data = new HashMap<>();
        data.put("total",productMapper.getProductCountByName("%" + productName + "%"));
        data.put("rows",productList);
        return new Gson().toJson(data);
    }

    /**
     * 删除商品
     * @param id
     * @return
     */
    @RequestMapping("delProduct")
    String delProduct(int id) {
        productMapper.deleteByPrimaryKey(id);
        return ReturnData.success("删除成功");
    }

    /**
     * 修改商品描述
     * @return
     */
    @RequestMapping("changeProductBody")
    String changeProductBody(int id,String body) {
        Product product = productMapper.selectByPrimaryKey(id);
        product.setProductDetailed(body);
        productMapper.updateByPrimaryKey(product);
        return ReturnData.success("修改成功");
    }

    /**
     * 修改商品信息
     * @param id
     * @param productType
     * @param productDescribe
     * @param productName
     * @param code
     * @param seoTitle
     * @param seoKeyword
     * @param seoDescs
     * @return
     */
    @RequestMapping("changeProduct")
    String changeProduct(int id,String productType,String productDescribe,String productName,String productDescribe_en,String productName_en,String code,String seoTitle,String seoKeyword,String seoDescs) {
        Product p = productMapper.selectByPrimaryKey(id);
        ProductType pt = null;
        if(productType.indexOf("This") != -1) {
            String[] str = productType.split("-");
            pt = productTypeMapper.selectByPrimaryKey(Integer.parseInt(str[0]));
            p.setProductType(pt);
        }
        if(code != null && code.indexOf(";") != -1) {
            List<ProductImage> productImageList = productImageMapper.getProductImageByProduct(p);
            for(ProductImage pi : productImageList) {
                productImageMapper.deleteByPrimaryKey(pi.getId());
            }
            String[] str = code.split(";");
            for(int i=0;i<str.length;i++) {
                ProductImage pimage = new ProductImage();
                pimage.setImageUrl(str[i]);
                pimage.setProduct(p);
                productImageMapper.insertSelective(pimage);
            }
        }
        p.setProductDescribe(productDescribe);
        p.setProductName(productName);
        p.setProductDescribe_en(productDescribe_en);
        p.setProductName_en(productName_en);
        Seo seo = new Seo();
        seo.setTitle(seoTitle);
        seo.setKeyword(seoKeyword);
        seo.setDescs(seoDescs);
        seo.setId(p.getSeo().getId());
        seoMapper.updateByPrimaryKeySelective(seo);
        productMapper.updateByPrimaryKey(p);
        return ReturnData.success("修改成功");
    }

}
